package drds.configuration.db;

import drds.configuration.db.datasource.DataSourceBuilder;
import drds.configuration.db.datasource.DataSourceContext;
import drds.configuration.db.datasource.DataSourceIdToDataSourceConfigMapContext;
import drds.configuration.db.table_mapping.TableInfo;
import drds.configuration.db.table_mapping.TableMapping;
import drds.configuration.db.table_mapping.check.CheckTableBaseColumn;
import drds.configuration.db.xml_mapping.MapperFactory;
import drds.tools.$;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

@Slf4j
public class DataBaseManager {
    public static void init() {
        log.info("配置数据源 start");
        try {
            DataSourceBuilder.buildDataSourceIdToDataSourceConfigMap();
        } catch (Exception e) {
            log.error("配置数据源失败", $.printStackTraceToString(e));
            throw new RuntimeException(e);
        }
        log.info("配置数据源 end");
        //
        log.info("TableMapping 表结构初始化 start");
        tableMappingInit();
        log.info("TableMapping 表结构初始化 end");
        //
        log.info("对象字段映射初始化 start");
        objectColumnMappingInit();
        log.info("对象字段映射初始化 end");
    }

    public static void tableMappingInit() {
        TableMapping tableMapping = new TableMapping();
        tableMapping.buildAllModelAndTableInfoMapping($.rootPackageName);
        //进行表结果校验
        Enumeration<String> enumeration = DataSourceIdToDataSourceConfigMapContext.dataSourceIdToDataSourceConfigMap.keys();
        while (enumeration.hasMoreElements()) {
            String groupDataSourceId = enumeration.nextElement();
            log.warn("基础字段校验:" + groupDataSourceId);
            List<TableInfo> tableInfoList = new ArrayList<TableInfo>();
            for (TableInfo tableInfo : DataSourceIdToDataSourceConfigMapContext.getDataSourceIdToTableInfoListMap().get(groupDataSourceId)) {
                if (tableInfo.isCheckBaseColumn()) {
                    tableInfoList.add(tableInfo);
                }
            }
            DataSourceContext dataSourceContext = DataSourceIdToDataSourceConfigMapContext.dataSourceIdToDataSourceConfigMap.get(groupDataSourceId);
            Properties properties = dataSourceContext.getDataSourceConfig().getProperties();
            CheckTableBaseColumn.check(tableInfoList, properties);
        }
    }

    private static void objectColumnMappingInit() {
        MapperFactory.dtoClassScan();
        MapperFactory.mapperScan();
    }

}
